package com.example.lcode.backtrack;

import org.springframework.beans.factory.FactoryBean;

import java.math.BigDecimal;

/**
 * @version 1.0
 * @author: ChuJie_Lin
 * @since: 2021-12-11 14:11
 **/
public class Question306 {


    public boolean isAdditiveNumber(String num) {
        if (num.length() <= 2) {
            return false;
        }
        int firstIndex = 1;
        for (int i = firstIndex; i <= num.length() - 2; i++) {
            for (int j = i + 1; j <= num.length() - 1 ; j++) {
                boolean additiveNumber = isAdditiveNumber(num, 0, i, j, j);
                if (additiveNumber) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean isAdditiveNumber(String num, int fristStartIndex, int firstEndIndex,
                                     int secondIndex, int lastIndex) {
        if (secondIndex == num.length()) {
            return true;
        } else {
            int suit = isSuit(num.substring(fristStartIndex, firstEndIndex), num.substring(firstEndIndex, secondIndex),
                    num.substring(secondIndex, lastIndex));
            if (suit == 1) {
                fristStartIndex = firstEndIndex;
                firstEndIndex = secondIndex;
                secondIndex = lastIndex;
            } else if (suit == 0) {
                return false;
            } else if (suit == 2) {
                lastIndex = lastIndex + 1;
            }
        }
        boolean additiveNumber = false;
        for (int i = lastIndex; i <= num.length(); i++) {
            additiveNumber = isAdditiveNumber(num, fristStartIndex, firstEndIndex, secondIndex, i);
            if (additiveNumber == true) {
                break;
            }
        }
        return additiveNumber;
    }


    /**
     * @return 1 正确
     * @return 0 错误
     * @return 2 继续
     */
    private int isSuit(String fristNum, String sceondNum, String compareNum) {
        BigDecimal firNum = new BigDecimal(fristNum);
        BigDecimal secNum = new BigDecimal(sceondNum);
        compareNum = compareNum.equals("") ? "-1" : compareNum;
        BigDecimal comNum = new BigDecimal(compareNum);
        if (fristNum.substring(0, 1).equals("0") && fristNum.length() > 1 || sceondNum.substring(0, 1).equals("0") && sceondNum.length() > 1 ||
                !compareNum.equals("-1") && compareNum.substring(0, 1).equals("0") && compareNum.length() > 1) {
            return 0;
        }
        if (firNum.add(secNum).compareTo(comNum) > 0) {
            return 2;
        } else if (firNum.add(secNum).compareTo(comNum) == 0) {
            return 1;
        }
        return 0;
    }

    public static void main(String[] args) {
        Question306 question306 = new Question306();
        boolean additiveNumber = question306.isAdditiveNumber("112358");
        System.out.println(additiveNumber);
    }

}
